import { EditItem } from '@/utils/editor'
import { useEffect, useState } from 'react'
import { CloseOutlined, SettingOutlined, PlusOutlined, MenuOutlined, DeleteOutlined ,InboxOutlined} from '@ant-design/icons';
import { Button, Divider, Tabs, Popconfirm, message ,Image,Form, Col,Row, Switch, Input,Select,Drawer,Pagination} from 'antd';
import classNames from 'classnames'
import Mark from 'for-editor'
const { TabPane } = Tabs;
import { useDispatch, useSelector, IRouteComponentProps } from 'umi'
import styles from './editor.less'
import styles1 from '../knowledge.less'
import { Curlist, FileParams, MarkList } from '@/utils/knowledge';
import { uploadImage } from '@/services';
interface Edit {
    marklist: EditItem
}
interface Known {
    marklist: MarkList[],
    updateResult: {},
    fileList: FileParams[],
    fileSum: number
}
const editor: React.FC<IRouteComponentProps> = (props) => {
    const [curindex, setcurindex] = useState('' as unknown as number)
    const [flag, setflag] = useState(false)
    const { query: { id } } = props.location
    // console.log('id....',id)

    let dispatch = useDispatch()
    useEffect(() => {
        dispatch({
            type: 'editor/getMark',
            payload: {
                id
            }
        });
        dispatch({
            type: 'knowledge/getMark'
        })
    }, [])
    let Editor: Edit = useSelector(state => state.editor)
    const [visible, setvisible] = useState(false)
    const [visible1, setvisible1] = useState(false)
    const [curList, setcurList] = useState<Curlist>({} as Curlist)
    let know: Known = useSelector(state => state.knowledge)
    console.log(know, 'know...')
    // let dispatch = useDispatch()
    // useEffect(() => {
    //     dispatch({
    //         type: 'knowledge/getMark'
    //     });
    // }, [])
    // 设置
    function Tosetting(id: string) {
        // console.log(id)
        setvisible(true)
        const result = know.marklist.filter(item => item.id == id)[0]
        // console.log('result,,,,',result)
        setcurList(result)
    }
    // 删除
    function confirm() {
        message.warning({
            content: '访客无权进行该操作',
            duration: 1
        });
    }
    function confirm1() {
        props.history.go(-1)
        // message.warning({
        //     content: '访客无权进行该操作',
        //     duration: 1
        // });
    }
    function cancel() {

    }

    async function uploadImg(e: any) {
        // console.log(e.target.files)
        const form = new FormData()
        // console.log(e.target.files[0])
        const file = e.target.files[0]
        form.append('file', file)
        const result = await uploadImage(form as any)
        // console.log(result)
        if (result.statusCode == 201) {
            setcurList({ ...curList, cover: result.data.url })
        }
    }
    function changeImg() {
        message.warning({
            content: '访客无权进行该操作',
            duration: 1
        });
    }
    function close() {
        setvisible(false)
    }
    function close1() {
        setvisible1(false)
    }
    function showFile(page = 1) {
        setvisible1(true)
        dispatch({
            type: 'knowledge/getFiles',
            payload: {
                page
            }
        })

    }
    function changePage(page: number) {
        // console.log(page)
        dispatch({
            type: 'knowledge/getFiles',
            payload: {
                page
            }
        })
    }
    async function uploadfile(e: any) {
        // console.log(e.target.files)
        const form = new FormData()
        // console.log(e.target.files[0])
        const file = e.target.files[0]
        form.append('file', file)
        const result = await uploadImage(form as any)
        console.log(result)
        dispatch({
            type: 'knowledge/getFiles',
            payload: {
                page: 1
            }
        })
    }
    console.log(Editor, 'Editor...')
    if (!Object.keys(Editor.marklist).length) {
        return null;
    }

    return <div className={styles.editor} >
        <div className={styles.article}>
            <div className={styles.nav}>
                <Popconfirm
                    title="确认关闭？如果有内容变更，请先保存。"
                    onConfirm={confirm1}
                    onCancel={cancel}
                    okText="确认"
                    cancelText="取消"
                    placement="left"
                >
                    <CloseOutlined />
                </Popconfirm>
                
                <div>
                    <img src={Editor.marklist.cover} alt="" />
                    <span>{Editor.marklist.title}</span>
                </div>
                {/* <SettingOutlined /> */}
                <SettingOutlined onClick={() => { Tosetting(Editor.marklist.id) }}/>
            </div>
            <Button block>保存</Button>
            <div className={styles.save}>
                <span>{Editor.marklist.children.length}篇文章</span>
                <Button type="primary" icon={<PlusOutlined />}>
                    新建
                </Button>
            </div>
            <div className={styles.list}>
                {
                    Editor.marklist.children.map((item, index) => {
                        return <div className={curindex == index && flag ? styles.active : ''} key={item.id} onClick={() => {
                            setcurindex(index)
                            setflag(true)
                        }} >
                            <MenuOutlined />
                            <span>{item.title}</span>
                            <Popconfirm
                                title="确认删除?"
                                onConfirm={confirm}
                                onCancel={cancel}
                                okText="确认"
                                cancelText="取消"
                            >
                                <DeleteOutlined />
                            </Popconfirm>

                        </div>
                    })
                }
            </div>
        </div>
        <div className={styles.markdown}>
            {
                !flag ? <p>
                    请新建章节（或者选择章节进行编辑）
                </p> : <Mark style={{ width: '100%', height: '100%' }} value={flag ? Editor.marklist.children[curindex].content : ''} />
            }
        </div>


        <Drawer
            title="更新知识库"
            width={600}
            onClose={close}
            visible={visible}
            bodyStyle={{ paddingBottom: 80 }}
            footer={
                <div
                    style={{
                        textAlign: 'right',
                    }}
                >
                    <Button onClick={close} style={{ marginRight: 8 }}>
                        Cancel
              </Button>
                    <Button onClick={() => { changeImg() }} type="primary">
                        Submit
              </Button>
                </div>
            }
        >
            <Form hideRequiredMark>
                <Form.Item
                    name="name"
                    label="名称"
                    rules={[{ required: true, message: 'Please enter user name' }]}>
                    <Input
                        defaultValue={curList ? curList.title : ''}
                        placeholder="Please enter user name" style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item
                    name="description"
                    label="描述"
                    rules={[
                        {
                            required: true,
                            message: 'please enter url description',
                        },
                    ]}
                >
                    <Input.TextArea rows={4} placeholder="please enter url description" defaultValue={curList.summary} />
                </Form.Item>
                <div>
                    <span>评论：</span>
                    <Switch defaultChecked />
                </div>
            </Form>
            <div className={styles1.upload}>
                <span>封面:&emsp;</span>
                <div className={styles1.uploadImg}>
                    <label htmlFor="avatar">
                        {
                            curList.cover ? <img src={curList.cover} alt="" /> :
                                <div style={{ textAlign: 'center' }}>
                                    <InboxOutlined style={{ color: '#00f', fontSize: '30px' }} />
                                    <p>
                                        点击选择文件或将文件拖拽到此处
                                </p>
                                    <p>
                                        文件将上传到 OSS, 如未配置请先配置
                                </p>
                                </div>
                        }
                    </label>
                    <input type="file" id='avatar' onChange={(e) => { uploadImg(e) }} />
                    {
                        curList.cover ? <input placeholder="Basic usage" defaultValue={curList.cover} style={{ width: '100%', border: '1px solid #eee', height: '30px' }} /> :
                            <Input defaultValue='' />
                    }
                    <div style={{ margin: "10px 0" }}>
                        <Button style={{ marginRight: '20px' }} onClick={() => {
                            showFile()
                        }}>选择文件</Button>
                        <Button danger onClick={() => {
                            setcurList({ ...curList, cover: '' })
                        }}>移除</Button>
                    </div>
                </div>
            </div>
        </Drawer>

        <Drawer
            title="文件选择"
            width={700}
            onClose={close1}
            visible={visible1}
            bodyStyle={{ paddingBottom: 80 }}
            footer={null}
        >
            <Form layout="inline" hideRequiredMark>
                <Row gutter={70}>
                    <Col span={12}>
                        <Form.Item
                            name="name"
                            label="文件名"
                            rules={[{ required: true, message: '请输入文件名' }]}
                        >
                            <Input placeholder="请输入知识库名称" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="url"
                            label="文件类型"
                            rules={[{ required: true, message: '请选择状态' }]}
                        >
                            <Input placeholder="请选择文件类型" />
                        </Form.Item>
                    </Col>
                </Row>
            </Form>

            <div className={styles1.rest}>
                <Button type="primary" >搜索</Button>
                <Button >重置</Button>
            </div>
            <div className={styles1.rest}>
                {/* <Button onClick={()=>{
                    uploadfile()
                }}>上传文件</Button> */}
                <label htmlFor="avatar2">
                    {/* <Button onClick={()=>{
                    uploadfile()
                }}>上传文件</Button> */}
                    <span>上传文件</span>
                </label>
                <input type="file" id='avatar2' onChange={(e) => { uploadfile(e) }} />
            </div>
            <div className={styles1.fileTable}>
                {
                    know.fileList.map(item => {
                        return <div key={item.id} className={styles1.fileTableItem}>
                            <Image.PreviewGroup>
                                <Image
                                    width='100%'
                                    height={120}
                                    src={item.url}
                                />
                            </Image.PreviewGroup>
                            {/* <img src={item.url} alt="" /> */}
                            <div className={styles1.fileItemOriginalname}>{item.originalname}</div>
                        </div>
                    })
                }
            </div>
            <div className={styles1.filefoot}>
                <b>共{know.fileSum}条</b>
                <Pagination defaultCurrent={1} total={know.fileSum} pageSizeOptions={['8', '12', '24', '36']} showSizeChanger defaultPageSize={12} onChange={(page) => {
                    changePage(page)
                }} />
            </div>
        </Drawer>
    </div>
}
export default editor